package com.jubaozan.framework.sentinel.config;

import com.jubaozan.framework.sentinel.generator.InstanceIdGenerator;
import java.util.Collections;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/19 15:08
 */

@Slf4j
@Configuration
public class InstanceIdGeneratorConfig {
    @Value("${framework.sentinel.instanceIdType:default}")
    private String generatorType;

    @Autowired(required = false) // 允许无实现
    private List<InstanceIdGenerator> generators = Collections.emptyList();

    @Bean
    @Primary
    public InstanceIdGenerator instanceIdGenerator() {
        // 根据类型查找匹配的生成器
        return generators.stream()
            .filter(gen -> matchesType(gen, generatorType))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException(
                "未找到类型为 '" + generatorType + "' 的IdGenerator实现"));
    }

    private boolean matchesType(InstanceIdGenerator generator, String type) {
        // 这里可以使用更复杂的匹配逻辑，例如通过注解或类名
        return generator.getClass().getSimpleName().equalsIgnoreCase(type + "InstanceIdGenerator");
    }
}
